//statTable.cpp
#include "statTable.h"
#include <stdio.h>

#include <string>
//---StatTable

int StatTable::initTable(int size)
{
	if(tableSize!=0 || size<270)
		return 0;
	tableSize=size;
	containersCounter=0;
	list=NULL;
	tableReseted=0;
	return createTable();
}
StatTable::StatTable()
{
	tableSize=0;
	initTable(0);
}
StatTable::StatTable(int size)
{
	tableSize=0;
	initTable(size);
}
StatTable::~StatTable()
{
	for(int i=0; i<tableSize; ++i)
	{
		delete list[i];
		list[i]=NULL;
	}
	delete[] list;
	list=NULL;
}
void StatTable::add(unsigned char* _values, int _size)
{
	if(containersCounter+2>=tableSize)
	{
		//printf("\n!%d!table reseting",(int)containersCounter);
		tableReseted=3;
		//getchar();
//		saveTable();
		clear();
	}
	
	list[exContCounter]->set(_values, _size);
	if(tableReseted>0)
	{
		++exContCounter;
		tableReseted-=2;	
	}
	else
	{
		if(tableReseted==-1)
		{
			tableReseted=0;
			list[containersCounter]->set(list[exContCounter]);
			containersCounter--;
		}
		++containersCounter;
		exContCounter=containersCounter;	
	}
}
void StatTable::deleteTable()
{
	for(int i=257; i<containersCounter; ++i)
	{
		delete list[i];
		list[i]=NULL;
	}
	containersCounter=exContCounter=257;
}
int StatTable::createTable()
{
	_HowManyBitsToWrite=8;
	containersCounter=0;
	list = new Vector*[tableSize];
	if(list==NULL)
		return 0;
	for(int i=0; i<tableSize; ++i)
		list[i]=NULL;
	
	unchar temp[256];
	containersCounter=0;
	for(long i=0; i<257; ++i)
	{
		temp[i]=i;
		list[containersCounter] = new Vector(&temp[i], 1);
		if(list[containersCounter]==NULL)
			return 0;
		++containersCounter;
		exContCounter=containersCounter;	
	}
	_HowManyBitsToWrite=9; 
	for(int i=257; i<tableSize+1; ++i) //
		list[i] = new Vector(0,0);   //
	return 1;
}
void StatTable::clear()
{
	containersCounter=257;
	//deleteTable();
	//createTable();  
	_HowManyBitsToWrite=9;  
}

void StatTable::saveTable()
{
	static int countTS;
	countTS++;
	std::string name="log_StatTable";
	int tempy=countTS;
	for(int i=3;i>=0;--i)
	{
		if(i>0)
			tempy=(countTS)/(10*i);
		else
			tempy=countTS;
		name+=(char)(48+(tempy%10));
	}	
	name+=".txt";
	FILE* file;
	file=fopen(name.c_str(),"wb");
	if(!file)
		return;
	for (int i=0; i < containersCounter; ++i)
	{
		fprintf(file, "%d ", (int)i);
		for(int j=0; j<list[i]->getSize(); ++j)
			fprintf(file,"%c ", list[i]->getValues()[j]);
		fprintf(file," [");
		for(int j=0; j<list[i]->getSize(); ++j)
			fprintf(file,"%d ", list[i]->getValues()[j]);
		fprintf(file,"] \n");
	}
	fprintf(file,"\n%d ",(int)containersCounter);
	fclose(file);
}
